#include "picloader.h"
#include <qpixmap.h>
#include <qimage.h>
#include <qdebug.h>
const int COUNT[]={1,2,-1,-2,0};
PicLoader::PicLoader(QObject *parent) :
	QThread(parent),pics(0),mutexs(0)
{

}
PicLoader::~PicLoader()
{
	if(pics)
		clear();
}

void PicLoader::run()
{
//qDebug()()<<"len="<<len;
	if(len<2) return;
atstart:
	runing=1;
	//qDebug()<<"start";
	quit=0;
	if(!pics)
		return;
	changed=0;
	mutex.lock();
	//qDebug()<<"nowR="<<*nowReading;
	int r=*nowReading,i;
	for(i=r+3;i<len;i++)
		if(pics[i])
		{
			mutexs[i].lock();
			delete pics[i];
			pics[i]=0;
			mutexs[i].unlock();
		}
	for(i=r-3;i>=0;i--)
		if(pics[i])
		{
			mutexs[i].lock();
			delete pics[i];
			pics[i]=0;
			mutexs[i].unlock();
		}
	mutex.unlock();
	for(int i=0;i<5;i++)
	{
		if(quit)
			return;
		if(r+COUNT[i]>=0 && r+COUNT[i]<len && !pics[r+COUNT[i]])
		{
			mutex.lock();
			QImage p(*folder+"/"+files->at(r+COUNT[i]));
			mutexs[r+COUNT[i]].lock();
			pics[r+COUNT[i]]=new QPixmap(QPixmap::fromImage(p));
			mutexs[r+COUNT[i]].unlock();
			mutex.unlock();
			if(changed)
				goto atstart;
		}
		//mutex.unlock();
	}
	runing=0;
	//qDebug()<<"over";
}
void PicLoader::setUp(QStringList *l, QString *s, int *n)
{
	files=l;folder=s;nowReading=n;
	//qDebug()<<"set up";
}
void PicLoader::reSet()
{

	if(pics)
	{
		clear();
	}
	if(mutexs)
	{
		delete [] mutexs;
		mutexs=0;
	}
	//qDebug()<<"pics="<<pics;
	len=files->length();
//qDebug()()<<"reset len="<<len;
	//qDebug()<<"len="<<len;
	if(len<2)
		return;
	pics = new QPixmap*[len];
	mutexs = new QMutex[len];
	if(!pics)
		return;
	memset(pics,0,sizeof(QPixmap *)*len);
	quit=0;
	changed=0;
}
void PicLoader::clear()
{
	if(!pics) return;
	int i;
	for(i=0;i<len;i++)
		if(pics[i])
			delete pics[i];
	delete [] pics;
	pics=0;
}
void PicLoader::stop()
{
	quit=1;
}
void PicLoader::change()
{
	changed = 1;
}
